package util;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 石小俊
 * Cookie工具类
 */
public class CookieUtil {

    /**
     * 添加cookie
     * @param name
     * @param value
     * @param response
     */
    public static void addCookie(String name, String value, HttpServletResponse response) {
        Cookie cookie = new Cookie(name, value);
        response.addCookie(cookie);
    }

    /**
     * 添加cookie,并设置该cookie的生存时间
     * @param name
     * @param value
     * @param maxAge 生存时间,单位:秒
     */
    public static void addCookie(String name, String value, int maxAge, HttpServletResponse response) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

    /**
     * 删除指定name的cookie,本质上使用的是添加操作,只是将其生存时间设置为0
     * @param name
     * @param response
     */
    public static void removeCookie(String name, HttpServletResponse response) {
        addCookie(name, "", 0, response);
    }

    public static void modifyCookie(String name, String value, HttpServletResponse response) {
        addCookie(name, value, response);
    }

    public static void modifyCookie(String name, String value, int maxAge, HttpServletResponse response) {
        addCookie(name, value, maxAge, response);
    }

    public static String findByName(String name, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (name.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }

}
